import axios from 'axios';
import {getAuthCookie, removeAuthCookie} from './auth';
import router from '@/router';

const config = require('./config')
const options = {
    baseURL: process.env.NODE_ENV ? config.devHost : config.host,
    timeout: 10000 // 5 seconds
}

const instance = axios.create(options);

instance.interceptors.request.use(config => {
    const token = getAuthCookie();
    if (token) {
        config.headers['Authorization'] = `Bearer ${token}`;
    }
    return config;
}, error => {
    return Promise.reject(error);
});

// 响应拦截器（处理 401 错误，跳转到登录页面）  改
instance.interceptors.response.use(function (response) {
    let {data, status} = response
    if (status === 200) {
        return data
    } else if (status === 401) {
        // 如果是 401 错误，跳转到登录页
        router.push({name: 'login'});
        removeAuthCookie();
    }
}, function (error) {
    return Promise.reject(error);
})
export default instance;

